/**
 * api路由
 */
var express = require('express'),
    helper = require('../../libs/helper'),
    logger = require('../../libs/logger').logger,
    router = express.Router(),
    expressjwt = require('express-jwt'),
    jwt = require('jsonwebtoken'),
    secret = "lovelyelfpop";


router.use(expressjwt({
  secret: secret,
  getToken: function fromHeaderOrQuerystring(req) {
    if (req.query && req.query._token) {
      return req.query._token;
    }
    else if (req.body && req.body._token) {
      return req.body._token;
    }
    return null;
  }
}).unless({
  path: ['/api/login', '/api/register']
}));

/**
 * 登录
 */
router.route('/login').post((req, res) => {
    logger.debug('router api login');

    var username = req.body.username;
    var password = req.body.password;
    if (!username) {
        return res.status(401).send("用户名不能为空");
    }
    if (!password) {
        return res.status(401).send("密码不能为空");
    }
    if (username != "admin" && password != "123") {
        return res.status(401).send("用户名或密码错误");
    }
    var authToken = jwt.sign({username: username}, secret);
    res.json({
        success: true,
        token: authToken
    });
});


router.use('/rest/notes', require('./notes_rest'));
router.use('/ajax/notes', require('./notes_ajax'));


var notFound = function (req, res) {
    res.send(404, {
        success: false,
        message: 'api接口未找到'
    });
};
router.route('*').get(notFound).post(notFound).put(notFound).delete(notFound);


module.exports = router;